package app.nbdevices.api.service.impl;

import app.nbdevices.api.dto.*;
import app.nbdevices.api.service.ApiService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import org.apache.poi.hssf.record.DVALRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import refactor.entity.*;
import refactor.mapper.*;
import refactor.service.IRoleService;


import javax.persistence.criteria.CriteriaBuilder;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApiServiceImpl implements ApiService {

    @Autowired
    RegionMapper regionMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    ModuleMapper moduleMapper;

    @Autowired
    FacilitiesMapper facilitiesMapper;

    @Autowired
    DeviceMapper deviceMapper;

    @Autowired
    OrganizationMapper organizationMapper;

    @Autowired
    RoleMapper roleMapper;

    @Override
    public List<RegionOrgDto> getRegOrgList() {
        return regionMapper.selectAllReg();
    }

    @Override
    public List<UserInfo> getUserInfoList() {
        return userMapper.getUserInfoList();
    }

    @Override
    public List<Module> getModuleList() {
        QueryWrapper<Module> wrapper=new QueryWrapper<>();
        return moduleMapper.selectList(wrapper);
    }

    @Override
    public List<FacRegOrgDto> getFacRegOrgDto() {
        return facilitiesMapper.getFacRegOrgList();
    }

    @Override
    public List<String> updateFacCode(List<FacCode> facCodeList) {
        ArrayList<String> error=new ArrayList<>();
        for(FacCode facCode:facCodeList){
            Facilities facilities=new Facilities();
            facilities.setDescription(facCode.getFacilities_description());
            facilities.setCode(facCode.getCode());
            QueryWrapper<Facilities> qFac=new QueryWrapper<Facilities>().eq("description",facCode.getFacilities_description());
            if(facilitiesMapper.update(facilities,qFac)!=1){
                error.add(facCode.getCode());
            }
        }
        return error;
    }

    @Override
    public List<DevInfoDto> getDevInfoList() {
        return deviceMapper.getDevInfoList();
    }

    @Override
    public int updateInsReg(InstitutionDto institutionDto) {

            Region region=new Region();
            region.setName(institutionDto.getRegion_name());

            if(regionMapper.selectList(new QueryWrapper<Region>().eq("name",region.getName())).size()!=0){
                return 0;
            }
            regionMapper.insert(region);

            Organization organization=new Organization();
            organization.setContact(institutionDto.getUser_name());
            organization.setName(institutionDto.getOrganization_name());
            organization.setContactEmail(institutionDto.getEmail());
            organization.setContactPhone(institutionDto.getPhone());
            organization.setContactAddress("");
            organization.setBusinessTerm(0l);
            organization.setContactSex("");
            organization.setCode("");
            organization.setLegalPersonName("");
            organization.setLegalPersonSex("");
            organization.setOrganizationCode("");
            QueryWrapper<Region> qReg=new QueryWrapper<Region>().eq("name",region.getName());
            organization.setRegionId(regionMapper.selectOne(qReg).getId());
            organization.setRegisteredAddress("");
            organization.setRegisteredCapital("");
            organization.setRegisteredDate(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")));
            organization.setBusinessTerm(0l);
            organization.setStatus("1");
            organization.setOrganizationType("0");
            organization.setReposal("0");
            organization.setWebSite("");
            organization.setType("");
            organization.setRegisteredNumber("");
            System.out.println(organization);
            organizationMapper.insert(organization);
        return 1;
    }

    @Override
    public int savaUserList(UserPostList userPostList) {

        QueryWrapper<Region> qr=new QueryWrapper<Region>().eq("name",userPostList.getRegion_name());
        List<Region> regions = regionMapper.selectList(qr);
        Integer regionId=regions.get(0).getId();
        QueryWrapper<Organization> qo=new QueryWrapper<Organization>().eq("region_id",regionId);
        //Integer id, Integer organizationId, Integer roleId, Integer regionId, String code, String name, String password, String nameDigest, String passwordDigest,
        // String realName, String sex, String idCard, String phoneNumber, String email, String qq,
        // String weChat, String openId, String avatar, Long registerTime, String frozen, String roleName, String authorityInfo
        List<Organization> organizations =organizationMapper.selectList(qo);
        Integer organizationId=organizations.get(0).getId();
        List<UserDto> userDtoList=userPostList.getUserList();
        List<User> us=new ArrayList<>();
        Integer roleId;
       for(UserDto userDto:userDtoList){
           roleId=roleMapper.selectList(new QueryWrapper<Role>().eq("name",userDto.getRole())).get(0).getId();
          if(userMapper.selectList(new QueryWrapper<User>().eq("open_id", userDto.getOppenid())).size()!=0){
              break;
          }
           us.add(new User(organizationId,roleId,regionId,"",userDto.getUser_name(),userDto.getPassword(),
                   userDto.getName_digest(),userDto.getPassword_digest(),userDto.getReal_name(),"","",
                   userDto.getPhone(),userDto.getEmail(),"",userDto.getWx_chat(),userDto.getOppenid(),userDto.getAvator(),
                   userDto.getRegiter_time(),userDto.getIs_frezon(),userDto.getRole(),"user"));
       }
       if(us.size()==0){
           return 0;
       }
       return userMapper.lotInsertUser(us);
    }

    @Override
    public Map<String,Object> getUserStatus(String openId) {
       List<User> users=userMapper.selectList(new QueryWrapper<User>().eq("open_id",openId));
       HashMap<String,Object> res=new HashMap<>(2);
       if(users.size()==0){
           res.put("status","-1");
           res.put("roleId",0);
       }else{
           User user=users.get(0);
           res.put("status",user.getFrozen());
           res.put("roleId",user.getRoleId());
       }

       return res;
    }

    @Override
    public Integer getCodes(List<String> codes) {
        List<Integer> res=new ArrayList<>();
        Integer flag=0;
        for(String code:codes){
            List<Device> devices = deviceMapper.selectList(new QueryWrapper<Device>().eq("code", code));
            if(devices.size()!=0){
                if(devices.get(0).getModId()==1){
                    flag=1;
                }
            }
        }
        return flag;
    }

    @Override
    public int getRrgionIsExist(String name) {
        Region region = regionMapper.selectOne(new QueryWrapper<Region>().eq("name", name));
        System.out.println(region);
        if(region==null){
            return 0;
        }
        return 1;
    }

    @Override
    public int setUserFrozen(String oppendId, Integer isFrozen) {

        List<User> users = userMapper.selectList(new QueryWrapper<User>().eq("open_id", oppendId));
        if(users.size()!=0){
            User u=users.get(0);
            Integer userFrozen=Integer.parseInt(u.getFrozen());
            //冻结
            if(userFrozen==1&&isFrozen==0){
                u.setFrozen("0");
                return userMapper.updateById(u);
            }
            //解冻
            if(userFrozen==0&&isFrozen==1){
                List<User> userFrozens = userMapper.selectList(new QueryWrapper<User>().eq("frozen", "1").eq("region_id", u.getRegionId()));
                for(User user: userFrozens){
                    user.setFrozen("0");
                    userMapper.updateById(user);
                }
                u.setFrozen("1");
                return userMapper.updateById(u);
            }
        }

        return 0;
    }
}
